/*
 * @Author: duapple
 * @Date: 2021-09-28 09:16:21
 * @LastEditTime: 2021-10-07 22:13:31
 * @LastEditors: duapple
 * @Description: Add description
 * @FilePath: /gen_cmake/main.go
 * Copyright (c) 2011 duapple - All rights reserved.
 */
package main

import (
	"flag"
	"fmt"
	log "fmt"
	"io"
	"os"
	"path/filepath"
	"runtime"
)

var gen_cmake_conf string = "tools/gen_cmake.conf"
var gen_cross_cmake_conf string = "tools/gen_cross_cmake.conf"

func main() {
	log.Println("gen_cmake tool start")

	tool_dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	work_dir, _ := os.Getwd()

	if runtime.GOOS == "linux" {
		tool_dir = "/usr/local/sbin/"
	}

	var conf_type string
	cross_flag := flag.Bool("c", false, "generate cross compile CMakeLists.txt")
	flag.Parse()
	if *cross_flag {
		conf_type = gen_cross_cmake_conf
	} else {
		conf_type = gen_cmake_conf
	}

	dst := filepath.Join(work_dir, "CMakeLists.txt")
	if _, err := os.Stat(dst); err == nil {
		log.Println("Current dir CMakeLists.txt has existed. Overwrite ?")
		var input string
		for (input == "Y") == false || (input == "N") == false {
			fmt.Println("Please Enter [Y/N]")
			fmt.Scanf("%s\n", &input)
			if input == "N" {
				log.Println("CMakeLists.txt is not generated. \n Quit")
				return
			} else if input == "Y" {
				break
			}
		}
	}

	var conf_dir string
	conf_dir = filepath.Join(tool_dir, filepath.Clean(conf_type))

	if _, err := copy(conf_dir, dst); err != nil {
		log.Println(conf_dir)
		log.Println("Generate FAILED. CMakeLists.txt is not generated.")
	}

}

func copy(src, dst string) (int64, error) {
	sourceFileStat, err := os.Stat(src)
	if err != nil {
		return 0, err
	}
	if !sourceFileStat.Mode().IsRegular() {
		return 0, fmt.Errorf("%s is not a regular file", src)
	}

	source, err := os.Open(src)
	if err != nil {
		return 0, err
	}
	defer source.Close()

	destination, err := os.Create(dst)
	if err != nil {
		return 0, err
	}
	defer destination.Close()

	nBytes, err := io.Copy(destination, source)
	return nBytes, err
}
